<template>
    <div class="todo-container">
      <div class="todo-wrap">
        <TodoHeader :addTodo="addTodo"/>
        <TodoList :todos="todos" />
        <TodoFooter :todos="todos" :delete-complete-todos="deleteCompleteTodos" :select-all-todos="selectAllTodos"/>

      </div>
    </div>
</template>

<script>
import PubSub from 'pubsub-js'
import TodoHeader from "./components/TodoHeader";
import TodoList from "./components/TodoList";
import TodoFooter from "./components/TodoFooter";
import storageUtil from "./util/storageUtil";

export default {

  data() {
    return {
      // todos: JSON.parse(window.localStorage.getItem('todos_key') || '[]')
      todos: storageUtil.readTodos()
    }

  },
  mounted() {
  //  订阅消息
    PubSub.subscribe('deleteTodo', (msg, index) => {
      this.deleteTodo(index)
    })
  },
  methods: {
    addTodo (todo) {
      this.todos.unshift(todo)
    },
    deleteTodo (index) {
      this.todos.splice(index, 1)
    },
    deleteCompleteTodos () {
      this.todos = this.todos.filter(todo => !todo.complete)
    },
    selectAllTodos (check) {
      this.todos = this.todos.filter(todo => todo.complete = check)
    }
  },

  watch: {
    todos: {
      deep: true,
      // handler: function (value) {
      //   window.localStorage.setItem('todos_key', JSON.stringify(value))
      // }
      handler: storageUtil.saveTodos
    }
  },
  //2 映射组件标签
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  },

}
</script>

<style>
/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
